<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="zh-cn">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>C#  制作Windows服务安装包 - 天添 - 博客园</title>
<link type="text/css" rel="stylesheet" href="/bundles/blog-common.css?v=Jsknfrse2BShd-7DrxM42RyulObn44e4JjkI6-WX6zk1"/>
<link id="MainCss" type="text/css" rel="stylesheet" href="/skins/UnlimitedSunlight/bundle-UnlimitedSunlight.css?v=2L2gyfQfiyCwU9MzHfZxHdlKAqdUmCTHT9X4c3k8hhc1"/>
<link title="RSS" type="application/rss+xml" rel="alternate" href="http://www.cnblogs.com/fantiantian/rss"/>
<link title="RSD" type="application/rsd+xml" rel="EditURI" href="http://www.cnblogs.com/fantiantian/rsd.xml"/>
<link type="application/wlwmanifest+xml" rel="wlwmanifest" href="http://www.cnblogs.com/fantiantian/wlwmanifest.xml"/>
<script src="http://common.cnblogs.com/script/jquery.js" type="text/javascript"></script>  
<script type="text/javascript">var currentBlogApp = 'fantiantian', cb_enable_mathjax=false;</script>
<script src="/bundles/blog-common.js?v=V3tkfsuahqfUzgmqZVwj2QjsxodIvgDfvPKdn8yDuMY1" type="text/javascript"></script>
</head>
<body>
<a name="top"></a>

<!--done-->
<div id="home">
<div id="header">
	<div id="blogTitle">
	<a id="lnkBlogLogo" href="http://www.cnblogs.com/fantiantian/"><img id="blogLogo" src="/Skins/custom/images/logo.gif" alt="返回主页" /></a>			
		
<!--done-->
<h1><a id="Header1_HeaderTitle" class="headermaintitle" href="http://www.cnblogs.com/fantiantian/">天添</a></h1>
<h2></h2>



		
	</div><!--end: blogTitle 博客的标题和副标题 -->
	<div id="navigator">
		
<ul id="navList">
<li><a id="MyLinks1_HomeLink" class="menu" href="http://www.cnblogs.com/">博客园</a></li>
<li><a id="MyLinks1_MyHomeLink" class="menu" href="http://www.cnblogs.com/fantiantian/">首页</a></li>
<li><a id="MyLinks1_NewPostLink" class="menu" rel="nofollow" href="http://i.cnblogs.com/EditPosts.aspx?opt=1">新随笔</a></li>
<li><a id="MyLinks1_ContactLink" class="menu" rel="nofollow" href="http://msg.cnblogs.com/send/%E5%A4%A9%E6%B7%BB">联系</a></li>
<li><a id="MyLinks1_Syndication" class="menu" href="http://www.cnblogs.com/fantiantian/rss">订阅</a>
<!--<a id="MyLinks1_XMLLink" class="aHeaderXML" href="http://www.cnblogs.com/fantiantian/rss"><img src="http://www.cnblogs.com/images/xml.gif" alt="订阅" /></a>--></li>
<li><a id="MyLinks1_Admin" class="menu" rel="nofollow" href="http://i.cnblogs.com/">管理</a></li>
</ul>
		<div class="blogStats">
			
			
<!--done-->
随笔- 36&nbsp;
文章- 9&nbsp;
评论- 70&nbsp;

			
		</div><!--end: blogStats -->
	</div><!--end: navigator 博客导航栏 -->
</div><!--end: header 头部 -->

<div id="main">
	<div id="mainContent">
	<div class="forFlow">
		
<div id="post_detail">
<!--done-->
<div id="topics">
	<div class = "post">
		<h1 class = "postTitle">
			<a id="cb_post_title_url" class="postTitle2" href="http://www.cnblogs.com/fantiantian/p/3419401.html">C#  制作Windows服务安装包</a>
		</h1>
		<div class="clear"></div>
		<div class="postBody">
			<div id="cnblogs_post_body"><p>&nbsp; &nbsp; &nbsp; &nbsp;这两天公司要用C#写一个windows服务，做成安装安装包。制作的过程中遇到了一些问题，写完之后总结一下。如果以后在用到的话可以可以参考一下，而且由于原来没有做过，不知道这样做是对是不对，请各位看官如果发现有不当之处请指教。</p>
<p>&nbsp; &nbsp; &nbsp; 开始的时候我的开发工具VS 2012，需要用<span>InstallShield，没闹明白，时间紧迫没有搞，改用vs2010。</span></p>
<p><span>&nbsp; &nbsp; &nbsp; 首先创建一个windows服务：</span></p>
<p><span>&nbsp;<img style="display: block; margin-left: auto; margin-right: auto;" src="http://images.cnitblog.com/blog/255323/201311/12112908-ae0569e9245b499e85865318bb9cb98c.png" alt="" /></span></p>
<p><strong>&nbsp; &nbsp; &nbsp; </strong>添加安装程序:<strong>&nbsp; &nbsp; &nbsp;</strong></p>
<p><strong><img style="display: block; margin-left: auto; margin-right: auto;" src="http://images.cnitblog.com/blog/255323/201311/12113217-415fcdc148364a87afbe5ffe1ea7746d.png" alt="" width="961" height="583" /></strong><strong>&nbsp; &nbsp; &nbsp; </strong>设置服务的属性：<strong>&nbsp;&nbsp;</strong></p>
<p><strong><img style="display: block; margin-left: auto; margin-right: auto;" src="http://images.cnitblog.com/blog/255323/201311/12113727-0ee318f6cf254868963a5e0895471f36.png" alt="" width="976" height="421" /></strong></p>
<p><em><strong>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;</strong></em>这里面简单设置一下服务的属性，ServiceName就是服务的名称，DispalyName是在本地服务列表中现实的名称，如果DispalyName没有设置，那么默认为ServiceName。StartType是服务的启动方式，Automatic为服务开机启动，Manual是手动。设置如下：</p>
<p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;<img style="display: block; margin-left: auto; margin-right: auto;" src="http://images.cnitblog.com/blog/255323/201311/12114443-705cc0897bcd4ec6b8cfd87b5cf00c6d.png" alt="" /></p>
<p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; OK下面开始搞一下服务的逻辑部分</p>
<p><strong>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </strong>服务逻辑：</p>
<p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<img style="display: block; margin-left: auto; margin-right: auto;" src="http://images.cnitblog.com/blog/255323/201311/12121806-7b28fa27e8ae4b83a694234da924d206.jpg" alt="" /></p>
<p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 就是写一个Soket服务端，在Service1.cd文件中有如下代码段：</p>
<p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;</p>
<div class="cnblogs_code">
<pre><span style="color: #008080;">1</span>         <span style="color: #0000ff;">protected</span> <span style="color: #0000ff;">override</span> <span style="color: #0000ff;">void</span> OnStart(<span style="color: #0000ff;">string</span><span style="color: #000000;">[] args)
</span><span style="color: #008080;">2</span> <span style="color: #000000;">        {
</span><span style="color: #008080;">3</span> 
<span style="color: #008080;">4</span> <span style="color: #000000;">        }
</span><span style="color: #008080;">5</span> 
<span style="color: #008080;">6</span>         <span style="color: #0000ff;">protected</span> <span style="color: #0000ff;">override</span> <span style="color: #0000ff;">void</span><span style="color: #000000;"> OnStop()
</span><span style="color: #008080;">7</span> <span style="color: #000000;">        {
</span><span style="color: #008080;">8</span> 
<span style="color: #008080;">9</span>         }</pre>
</div>
<p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 从字面理解也很容易，一个是服务启动时候一个是服务停止时候调用的方法，</p>
<p>&nbsp; &nbsp; 我定义了一个处理Socket的帮助类SocketHandle.cs<em style="line-height: 1.5;">&nbsp;<br /></em></p>
<div class="cnblogs_code">
<pre><span style="color: #008080;">  1</span> <span style="color: #0000ff;">using</span><span style="color: #000000;"> System;
</span><span style="color: #008080;">  2</span> <span style="color: #0000ff;">using</span><span style="color: #000000;"> System.Collections.Generic;
</span><span style="color: #008080;">  3</span> <span style="color: #0000ff;">using</span><span style="color: #000000;"> System.Linq;
</span><span style="color: #008080;">  4</span> <span style="color: #0000ff;">using</span><span style="color: #000000;"> System.Text;
</span><span style="color: #008080;">  5</span> <span style="color: #0000ff;">using</span><span style="color: #000000;"> System.Net.Sockets;
</span><span style="color: #008080;">  6</span> <span style="color: #0000ff;">using</span><span style="color: #000000;"> System.Net;
</span><span style="color: #008080;">  7</span> <span style="color: #0000ff;">using</span><span style="color: #000000;"> System.Threading;
</span><span style="color: #008080;">  8</span> 
<span style="color: #008080;">  9</span> <span style="color: #0000ff;">namespace</span><span style="color: #000000;"> SocketServer
</span><span style="color: #008080;"> 10</span> <span style="color: #000000;">{
</span><span style="color: #008080;"> 11</span>     <span style="color: #0000ff;">class</span><span style="color: #000000;"> SocketHandle
</span><span style="color: #008080;"> 12</span> <span style="color: #000000;">    {
</span><span style="color: #008080;"> 13</span>         <span style="color: #0000ff;">private</span> <span style="color: #0000ff;">static</span><span style="color: #000000;"> Socket serverSocket;
</span><span style="color: #008080;"> 14</span>         <span style="color: #0000ff;">int</span> pointInt = <span style="color: #800080;">8888</span><span style="color: #000000;">;
</span><span style="color: #008080;"> 15</span>         <span style="color: #0000ff;">private</span> <span style="color: #0000ff;">static</span> <span style="color: #0000ff;">byte</span>[] result = <span style="color: #0000ff;">new</span> <span style="color: #0000ff;">byte</span>[<span style="color: #800080;">1024</span><span style="color: #000000;">];
</span><span style="color: #008080;"> 16</span>         <span style="color: #0000ff;">private</span> <span style="color: #0000ff;">static</span><span style="color: #000000;"> SocketHandle socketHandle;
</span><span style="color: #008080;"> 17</span> 
<span style="color: #008080;"> 18</span>         <span style="color: #0000ff;">public</span><span style="color: #000000;"> SocketHandle()
</span><span style="color: #008080;"> 19</span> <span style="color: #000000;">        {
</span><span style="color: #008080;"> 20</span> 
<span style="color: #008080;"> 21</span> <span style="color: #000000;">        }
</span><span style="color: #008080;"> 22</span> 
<span style="color: #008080;"> 23</span>         <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">static</span><span style="color: #000000;"> SocketHandle getInstance()
</span><span style="color: #008080;"> 24</span> <span style="color: #000000;">        {
</span><span style="color: #008080;"> 25</span>             <span style="color: #0000ff;">if</span> (socketHandle == <span style="color: #0000ff;">null</span><span style="color: #000000;">)
</span><span style="color: #008080;"> 26</span> <span style="color: #000000;">            {
</span><span style="color: #008080;"> 27</span>                 socketHandle = <span style="color: #0000ff;">new</span><span style="color: #000000;"> SocketHandle();
</span><span style="color: #008080;"> 28</span> <span style="color: #000000;">            }
</span><span style="color: #008080;"> 29</span> 
<span style="color: #008080;"> 30</span>             <span style="color: #0000ff;">return</span><span style="color: #000000;"> socketHandle;
</span><span style="color: #008080;"> 31</span> <span style="color: #000000;">        }
</span><span style="color: #008080;"> 32</span> 
<span style="color: #008080;"> 33</span>         <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">void</span><span style="color: #000000;"> InitSocketServer()
</span><span style="color: #008080;"> 34</span> <span style="color: #000000;">        {
</span><span style="color: #008080;"> 35</span>             IPAddress localIp =<span style="color: #000000;"> GetLocalIP();
</span><span style="color: #008080;"> 36</span>             <span style="color: #0000ff;">if</span> (localIp == <span style="color: #0000ff;">null</span><span style="color: #000000;">)
</span><span style="color: #008080;"> 37</span> <span style="color: #000000;">            {
</span><span style="color: #008080;"> 38</span>                 localIp = IPAddress.Parse(<span style="color: #800000;">"</span><span style="color: #800000;">127.0.0.1</span><span style="color: #800000;">"</span><span style="color: #000000;">);
</span><span style="color: #008080;"> 39</span> <span style="color: #000000;">            }
</span><span style="color: #008080;"> 40</span>             <span style="color: #0000ff;">try</span>
<span style="color: #008080;"> 41</span> <span style="color: #000000;">            {
</span><span style="color: #008080;"> 42</span>                 <span style="color: #0000ff;">if</span> (serverSocket == <span style="color: #0000ff;">null</span><span style="color: #000000;">)
</span><span style="color: #008080;"> 43</span> <span style="color: #000000;">                {
</span><span style="color: #008080;"> 44</span>                     serverSocket = <span style="color: #0000ff;">new</span><span style="color: #000000;"> Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);                  
</span><span style="color: #008080;"> 45</span>                     serverSocket.Bind(<span style="color: #0000ff;">new</span><span style="color: #000000;"> IPEndPoint(localIp, pointInt));
</span><span style="color: #008080;"> 46</span>                     serverSocket.Listen(<span style="color: #800080;">10</span><span style="color: #000000;">);
</span><span style="color: #008080;"> 47</span>                     Thread myThread = <span style="color: #0000ff;">new</span><span style="color: #000000;"> Thread(ListenClientConnect);
</span><span style="color: #008080;"> 48</span> <span style="color: #000000;">                    myThread.Start(); 
</span><span style="color: #008080;"> 49</span> 
<span style="color: #008080;"> 50</span> <span style="color: #000000;">                }
</span><span style="color: #008080;"> 51</span> <span style="color: #000000;">            }
</span><span style="color: #008080;"> 52</span>             <span style="color: #0000ff;">catch</span><span style="color: #000000;"> (Exception ex)
</span><span style="color: #008080;"> 53</span> <span style="color: #000000;">            { 
</span><span style="color: #008080;"> 54</span> <span style="color: #000000;">            }
</span><span style="color: #008080;"> 55</span> <span style="color: #000000;">        }
</span><span style="color: #008080;"> 56</span> 
<span style="color: #008080;"> 57</span> 
<span style="color: #008080;"> 58</span> 
<span style="color: #008080;"> 59</span>         <span style="color: #808080;">///</span> <span style="color: #808080;">&lt;summary&gt;</span>  
<span style="color: #008080;"> 60</span>         <span style="color: #808080;">///</span><span style="color: #008000;"> 监听客户端连接  
</span><span style="color: #008080;"> 61</span>         <span style="color: #808080;">///</span> <span style="color: #808080;">&lt;/summary&gt;</span>  
<span style="color: #008080;"> 62</span>         <span style="color: #0000ff;">private</span> <span style="color: #0000ff;">static</span> <span style="color: #0000ff;">void</span><span style="color: #000000;"> ListenClientConnect()
</span><span style="color: #008080;"> 63</span> <span style="color: #000000;">        {
</span><span style="color: #008080;"> 64</span>             <span style="color: #0000ff;">while</span> (<span style="color: #0000ff;">true</span><span style="color: #000000;">)
</span><span style="color: #008080;"> 65</span> <span style="color: #000000;">            {
</span><span style="color: #008080;"> 66</span>                 <span style="color: #0000ff;">try</span>
<span style="color: #008080;"> 67</span> <span style="color: #000000;">                {
</span><span style="color: #008080;"> 68</span>                     Socket clientSocket =<span style="color: #000000;"> serverSocket.Accept();
</span><span style="color: #008080;"> 69</span>                     Thread receiveThread = <span style="color: #0000ff;">new</span><span style="color: #000000;"> Thread(ReceiveMessage);
</span><span style="color: #008080;"> 70</span> <span style="color: #000000;">                    receiveThread.Start(clientSocket);
</span><span style="color: #008080;"> 71</span> <span style="color: #000000;">                }
</span><span style="color: #008080;"> 72</span>                 <span style="color: #0000ff;">catch</span><span style="color: #000000;"> (Exception ex)
</span><span style="color: #008080;"> 73</span> <span style="color: #000000;">                { 
</span><span style="color: #008080;"> 74</span> <span style="color: #000000;">                }
</span><span style="color: #008080;"> 75</span> <span style="color: #000000;">            }
</span><span style="color: #008080;"> 76</span> <span style="color: #000000;">        }
</span><span style="color: #008080;"> 77</span> 
<span style="color: #008080;"> 78</span> 
<span style="color: #008080;"> 79</span> 
<span style="color: #008080;"> 80</span>         <span style="color: #808080;">///</span> <span style="color: #808080;">&lt;summary&gt;</span>  
<span style="color: #008080;"> 81</span>         <span style="color: #808080;">///</span><span style="color: #008000;"> 接收消息  
</span><span style="color: #008080;"> 82</span>         <span style="color: #808080;">///</span> <span style="color: #808080;">&lt;/summary&gt;</span>  
<span style="color: #008080;"> 83</span>         <span style="color: #808080;">///</span> <span style="color: #808080;">&lt;param name="clientSocket"&gt;&lt;/param&gt;</span>  
<span style="color: #008080;"> 84</span>         <span style="color: #0000ff;">private</span> <span style="color: #0000ff;">static</span> <span style="color: #0000ff;">void</span> ReceiveMessage(<span style="color: #0000ff;">object</span><span style="color: #000000;"> clientSocket)
</span><span style="color: #008080;"> 85</span> <span style="color: #000000;">        {
</span><span style="color: #008080;"> 86</span>             Socket myClientSocket =<span style="color: #000000;"> (Socket)clientSocket; 
</span><span style="color: #008080;"> 87</span>             <span style="color: #0000ff;">byte</span>[] bs = <span style="color: #0000ff;">new</span> <span style="color: #0000ff;">byte</span>[<span style="color: #800080;">1024</span><span style="color: #000000;">];
</span><span style="color: #008080;"> 88</span>             <span style="color: #0000ff;">while</span> (<span style="color: #0000ff;">true</span><span style="color: #000000;">)
</span><span style="color: #008080;"> 89</span> <span style="color: #000000;">            {
</span><span style="color: #008080;"> 90</span>                 <span style="color: #0000ff;">try</span>
<span style="color: #008080;"> 91</span> <span style="color: #000000;">                {
</span><span style="color: #008080;"> 92</span>                     <span style="color: #008000;">//</span><span style="color: #008000;">通过clientSocket接收数据  </span>
<span style="color: #008080;"> 93</span>                     <span style="color: #0000ff;">int</span> receiveNumber =<span style="color: #000000;"> myClientSocket.Receive(result);
</span><span style="color: #008080;"> 94</span>                     <span style="color: #0000ff;">string</span> data = Encoding.ASCII.GetString(result, <span style="color: #800080;">0</span><span style="color: #000000;">, receiveNumber);
</span><span style="color: #008080;"> 95</span>                     bs = Encoding.ASCII.GetBytes(<span style="color: #800000;">"</span><span style="color: #800000;">Receive Data </span><span style="color: #800000;">"</span>+<span style="color: #000000;">data);
</span><span style="color: #008080;"> 96</span> <span style="color: #000000;">                }
</span><span style="color: #008080;"> 97</span>                 <span style="color: #0000ff;">catch</span><span style="color: #000000;"> (Exception ex)
</span><span style="color: #008080;"> 98</span> <span style="color: #000000;">                {
</span><span style="color: #008080;"> 99</span> <span style="color: #000000;">                    myClientSocket.Shutdown(SocketShutdown.Both);
</span><span style="color: #008080;">100</span>                     myClientSocket.Send(bs, bs.Length, <span style="color: #800080;">0</span>);  <span style="color: #008000;">//</span><span style="color: #008000;">返回信息给客户端</span>
<span style="color: #008080;">101</span> <span style="color: #000000;">                    myClientSocket.Close(); 
</span><span style="color: #008080;">102</span>                     <span style="color: #0000ff;">break</span><span style="color: #000000;">;
</span><span style="color: #008080;">103</span> <span style="color: #000000;">                }
</span><span style="color: #008080;">104</span>                 myClientSocket.Send(bs, bs.Length, <span style="color: #800080;">0</span><span style="color: #000000;">);
</span><span style="color: #008080;">105</span> <span style="color: #000000;">                myClientSocket.Close();
</span><span style="color: #008080;">106</span>                 <span style="color: #0000ff;">break</span><span style="color: #000000;">;
</span><span style="color: #008080;">107</span> <span style="color: #000000;">            }
</span><span style="color: #008080;">108</span> 
<span style="color: #008080;">109</span> <span style="color: #000000;">        }
</span><span style="color: #008080;">110</span> 
<span style="color: #008080;">111</span>         <span style="color: #808080;">///</span> <span style="color: #808080;">&lt;summary&gt;</span>
<span style="color: #008080;">112</span>         <span style="color: #808080;">///</span><span style="color: #008000;"> 获取本地IP地址
</span><span style="color: #008080;">113</span>         <span style="color: #808080;">///</span> <span style="color: #808080;">&lt;/summary&gt;</span>
<span style="color: #008080;">114</span>         <span style="color: #808080;">///</span> <span style="color: #808080;">&lt;returns&gt;&lt;/returns&gt;</span>
<span style="color: #008080;">115</span>         <span style="color: #0000ff;">private</span><span style="color: #000000;"> IPAddress GetLocalIP()
</span><span style="color: #008080;">116</span> <span style="color: #000000;">        {
</span><span style="color: #008080;">117</span>             IPAddress localIp = <span style="color: #0000ff;">null</span><span style="color: #000000;">;
</span><span style="color: #008080;">118</span>             <span style="color: #0000ff;">try</span>
<span style="color: #008080;">119</span> <span style="color: #000000;">            {
</span><span style="color: #008080;">120</span> <span style="color: #000000;">                IPAddress[] ipArray;
</span><span style="color: #008080;">121</span>                 ipArray =<span style="color: #000000;"> Dns.GetHostAddresses(Dns.GetHostName());
</span><span style="color: #008080;">122</span> 
<span style="color: #008080;">123</span>                 localIp = ipArray.First(ip =&gt; ip.AddressFamily ==<span style="color: #000000;"> AddressFamily.InterNetwork);
</span><span style="color: #008080;">124</span> <span style="color: #000000;">            }
</span><span style="color: #008080;">125</span>             <span style="color: #0000ff;">catch</span><span style="color: #000000;"> (Exception ex)
</span><span style="color: #008080;">126</span> <span style="color: #000000;">            { 
</span><span style="color: #008080;">127</span> <span style="color: #000000;">            }
</span><span style="color: #008080;">128</span> 
<span style="color: #008080;">129</span>             <span style="color: #0000ff;">return</span><span style="color: #000000;"> localIp;
</span><span style="color: #008080;">130</span> <span style="color: #000000;">        }
</span><span style="color: #008080;">131</span> <span style="color: #000000;">    }
</span><span style="color: #008080;">132</span> }</pre>
</div>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 在Service1.cs文件中写成如下形式：</p>
<div class="cnblogs_code">
<pre><span style="color: #008080;"> 1</span> <span style="color: #0000ff;">using</span><span style="color: #000000;"> System;
</span><span style="color: #008080;"> 2</span> <span style="color: #0000ff;">using</span><span style="color: #000000;"> System.Collections.Generic;
</span><span style="color: #008080;"> 3</span> <span style="color: #0000ff;">using</span><span style="color: #000000;"> System.ComponentModel;
</span><span style="color: #008080;"> 4</span> <span style="color: #0000ff;">using</span><span style="color: #000000;"> System.Data;
</span><span style="color: #008080;"> 5</span> <span style="color: #0000ff;">using</span><span style="color: #000000;"> System.Diagnostics;
</span><span style="color: #008080;"> 6</span> <span style="color: #0000ff;">using</span><span style="color: #000000;"> System.Linq;
</span><span style="color: #008080;"> 7</span> <span style="color: #0000ff;">using</span><span style="color: #000000;"> System.ServiceProcess;
</span><span style="color: #008080;"> 8</span> <span style="color: #0000ff;">using</span><span style="color: #000000;"> System.Text;
</span><span style="color: #008080;"> 9</span> <span style="color: #0000ff;">using</span><span style="color: #000000;"> System.Threading;
</span><span style="color: #008080;">10</span> 
<span style="color: #008080;">11</span> <span style="color: #0000ff;">namespace</span><span style="color: #000000;"> SocketServer
</span><span style="color: #008080;">12</span> <span style="color: #000000;">{
</span><span style="color: #008080;">13</span>     <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">partial</span> <span style="color: #0000ff;">class</span><span style="color: #000000;"> Service1 : ServiceBase
</span><span style="color: #008080;">14</span> <span style="color: #000000;">    {
</span><span style="color: #008080;">15</span>         <span style="color: #0000ff;">private</span><span style="color: #000000;"> Thread thread;
</span><span style="color: #008080;">16</span> 
<span style="color: #008080;">17</span>         <span style="color: #0000ff;">public</span><span style="color: #000000;"> Service1()
</span><span style="color: #008080;">18</span> <span style="color: #000000;">        {
</span><span style="color: #008080;">19</span> <span style="color: #000000;">            InitializeComponent();
</span><span style="color: #008080;">20</span> <span style="color: #000000;">        }
</span><span style="color: #008080;">21</span> 
<span style="color: #008080;">22</span>         <span style="color: #808080;">///</span> <span style="color: #808080;">&lt;summary&gt;</span>
<span style="color: #008080;">23</span>         <span style="color: #808080;">///</span><span style="color: #008000;"> 服务启动的时候，初始化socket服务。
</span><span style="color: #008080;">24</span>         <span style="color: #808080;">///</span> <span style="color: #808080;">&lt;/summary&gt;</span>
<span style="color: #008080;">25</span>         <span style="color: #0000ff;">private</span> <span style="color: #0000ff;">void</span><span style="color: #000000;"> RequestHandle()
</span><span style="color: #008080;">26</span> <span style="color: #000000;">        {
</span><span style="color: #008080;">27</span>             <span style="color: #0000ff;">try</span>
<span style="color: #008080;">28</span> <span style="color: #000000;">            {
</span><span style="color: #008080;">29</span>                 SocketHandle socketHandle =<span style="color: #000000;"> SocketHandle.getInstance();
</span><span style="color: #008080;">30</span> <span style="color: #000000;">                socketHandle.InitSocketServer();
</span><span style="color: #008080;">31</span> <span style="color: #000000;">            }
</span><span style="color: #008080;">32</span>             <span style="color: #0000ff;">catch</span><span style="color: #000000;"> (Exception ex)
</span><span style="color: #008080;">33</span> <span style="color: #000000;">            { 
</span><span style="color: #008080;">34</span> <span style="color: #000000;">            }
</span><span style="color: #008080;">35</span> <span style="color: #000000;">        }
</span><span style="color: #008080;">36</span> 
<span style="color: #008080;">37</span>         <span style="color: #0000ff;">protected</span> <span style="color: #0000ff;">override</span> <span style="color: #0000ff;">void</span> OnStart(<span style="color: #0000ff;">string</span><span style="color: #000000;">[] args)
</span><span style="color: #008080;">38</span> <span style="color: #000000;">        { 
</span><span style="color: #008080;">39</span>             thread = <span style="color: #0000ff;">new</span> Thread(<span style="color: #0000ff;">new</span> ThreadStart(<span style="color: #0000ff;">this</span><span style="color: #000000;">.RequestHandle));
</span><span style="color: #008080;">40</span> <span style="color: #000000;">            thread.Start();
</span><span style="color: #008080;">41</span> <span style="color: #000000;">        }
</span><span style="color: #008080;">42</span> 
<span style="color: #008080;">43</span>         <span style="color: #0000ff;">protected</span> <span style="color: #0000ff;">override</span> <span style="color: #0000ff;">void</span><span style="color: #000000;"> OnStop()
</span><span style="color: #008080;">44</span> <span style="color: #000000;">        {  
</span><span style="color: #008080;">45</span> <span style="color: #000000;">            thread.Abort();
</span><span style="color: #008080;">46</span> <span style="color: #000000;">        }
</span><span style="color: #008080;">47</span> <span style="color: #000000;">    }
</span><span style="color: #008080;">48</span> }</pre>
</div>
<p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;OK，逻辑部分已经完成了，下面看关键的操作，将服务打包，首先在本解决方案中添加安装部署项目，<img style="display: block; margin-left: auto; margin-right: auto;" src="http://images.cnitblog.com/blog/255323/201311/12124441-fffb15471d7645bd83418795dc44fa41.png" alt="" width="944" height="566" /></p>
<p><img style="display: block; margin-left: auto; margin-right: auto;" src="http://images.cnitblog.com/blog/255323/201311/12124526-5270568f1ce74e0586a9d106c87355e8.png" alt="" /></p>
<p>&nbsp; 创建安装项目以后是这个样子的：&nbsp;</p>
<p><em id="__mceDel"><img style="display: block; margin-left: auto; margin-right: auto;" src="http://images.cnitblog.com/blog/255323/201311/12124629-5f7aee0113d64212bb56ced48bbbc95b.png" alt="" width="947" height="442" /></em></p>
<p>在应用程序文件夹中添加项目输出：</p>
<p><img style="display: block; margin-left: auto; margin-right: auto;" src="http://images.cnitblog.com/blog/255323/201311/12124839-496a8de59f7749f1a1d3789a18acdfbd.png" alt="" width="969" height="523" /></p>
<p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;选择SocketServer作为主输出：</p>
<p><img style="display: block; margin-left: auto; margin-right: auto;" src="http://images.cnitblog.com/blog/255323/201311/12125050-0be46104da6f43e2b9eaf137884cce18.png" alt="" /></p>
<p>创建自定义操作：</p>
<p><img style="display: block; margin-left: auto; margin-right: auto;" src="http://images.cnitblog.com/blog/255323/201311/12125148-eb9e418ac3944dbd9d7aee822ac8a221.png" alt="" /></p>
<p>选择自定义操作进入到自定义操作界面，在<span style="text-decoration: underline;">自定义操作</span>上选择添加自定义操作：</p>
<p><img style="display: block; margin-left: auto; margin-right: auto;" src="http://images.cnitblog.com/blog/255323/201311/12125446-36c12ad1b137475f8b5e8249a067f92b.png" alt="" width="1110" height="374" /></p>
<p><em><strong>&nbsp; &nbsp; &nbsp;在弹出的选择项目中的项对话框中选择<span style="text-decoration: underline;">应用程序文件夹</span>中选择主输出项目：</strong></em></p>
<p><em><strong><img style="display: block; margin-left: auto; margin-right: auto;" src="http://images.cnitblog.com/blog/255323/201311/12125747-cc55ca9f908245228a2821d45a23cef7.png" alt="" /></strong></em></p>
<p>&nbsp;</p>
<p>然后分别重新生成SocketServer和SocketSetUp项目，查看解决方案的属性，</p>
<p><img style="display: block; margin-left: auto; margin-right: auto;" src="http://images.cnitblog.com/blog/255323/201311/12130137-3ef034fc509341dd8a83c31ad8f113ef.png" alt="" /></p>
<p>查看项目的配置，到对应的文件中去找安装文件，如果是Debug那么就去对应项目中的Debug目录下去找生成的文件，我们的目录是F:\SocketServer，所以得去F:\SocketServer\SocketSetUp\Debug目录去找安装文件。<img style="display: block; margin-left: auto; margin-right: auto;" src="http://images.cnitblog.com/blog/255323/201311/12130410-87e8c69292074346b120a9a70cb4ec4f.png" alt="" /></p>
<p>&nbsp;</p>
<p>下面安装一下看一下结果。(/ □ \)，在安装的时候让我填写服务器名称密码什么的</p>
<p><img style="display: block; margin-left: auto; margin-right: auto;" src="http://images.cnitblog.com/blog/255323/201311/12132051-8e7e88289ab247c0a5321e64073a1754.png" alt="" /></p>
<p>，按说我自己在电脑上装东西应该不需要授权啊，回头在看一下，问题出在安装程序上，看到serviceProcessInstaller1的属性的时候发现了授权的信息，Account这个选项中选择LocalSystem应该就是本地安装应该是权限最大的不需要额外授权。试试看吧。OK没有问题，安装成功。下面看一下咱们的逻辑是不是正确，先看已安装程序中是不是存在SocketSetUp程序</p>
<p><img src="http://images.cnitblog.com/blog/255323/201311/12132437-b41089c4b7ce4ffba94447bc86ad673d.png" alt="" /></p>
<p>没问题，下面在看一下我们SocketServer Release服务是不是运行正常：</p>
<p><img style="display: block; margin-left: auto; margin-right: auto;" src="http://images.cnitblog.com/blog/255323/201311/12132613-f3a664978df24a5899feb3150d9909fe.png" alt="" /></p>
<p>没问题，查看8888端口是不是处于监听状态：</p>
<p><img style="display: block; margin-left: auto; margin-right: auto;" src="http://images.cnitblog.com/blog/255323/201311/12132719-b19a989bff0947f88d7e3990e4d35db2.png" alt="" />没问题，运行一下Socket客户端，看一下结果：</p>
<p>&nbsp; &nbsp;<img style="display: block; margin-left: auto; margin-right: auto;" src="http://images.cnitblog.com/blog/255323/201311/12133028-052511442b604eb189b09e29ab2b1e27.png" alt="" />没问题，这样就算成功了，但是有个问题，由于服务所要开放的端口很多时候都是需要用户在安装的时候指定，那好吧，现在将Socke服务端的端口由用户指定。</p>
<p>&nbsp; &nbsp;在安装项目的视图中选择用户界面，在启动选项上右键添加对话框：<em id="__mceDel" style="line-height: 1.5;">&nbsp;</em></p>
<p><em id="__mceDel"><img style="display: block; margin-left: auto; margin-right: auto;" src="http://images.cnitblog.com/blog/255323/201311/12133701-da00279701aa4d1e9bdff81035b19201.png" alt="" /></em></p>
<p>&nbsp;</p>
<p>在弹出的添加对话框中选择文本框，设置文件框的属性：</p>
<p><img style="display: block; margin-left: auto; margin-right: auto;" src="http://images.cnitblog.com/blog/255323/201311/12133829-d19d0a1ea45d436ead8dd10de0725c62.png" alt="" /><img style="display: block; margin-left: auto; margin-right: auto;" src="http://images.cnitblog.com/blog/255323/201311/12133838-bf3ea1c620f5403b882261a5c195d86a.png" alt="" /></p>
<p>这样文本框就添加完了，文本框属性很简单的可以看出来，只需要一个，其他的都隐藏就好了，下面就如何获取用户输入的端口值，在自定义操作中的主输出xxxxx的属性选项卡中添加参数</p>
<p>下面只等着接收了，接收之后将指定的端口保存到本地的安装目录，这样还需要设置一个安装路径的参数应该是这样/Port="[PORT]" /targetdir="[TARGETDIR]/"</p>
<p><img style="display: block; margin-left: auto; margin-right: auto;" src="http://images.cnitblog.com/blog/255323/201311/12134900-6bdc59da372f4ef4a4e8808c8d93722d.png" alt="" /></p>
<p>俺写了一个XML的帮助类，用来保存端口：</p>
<div class="cnblogs_code">
<pre><span style="color: #008080;"> 1</span> <span style="color: #0000ff;">using</span><span style="color: #000000;"> System;
</span><span style="color: #008080;"> 2</span> <span style="color: #0000ff;">using</span><span style="color: #000000;"> System.Collections.Generic;
</span><span style="color: #008080;"> 3</span> <span style="color: #0000ff;">using</span><span style="color: #000000;"> System.Linq;
</span><span style="color: #008080;"> 4</span> <span style="color: #0000ff;">using</span><span style="color: #000000;"> System.Text;
</span><span style="color: #008080;"> 5</span> <span style="color: #0000ff;">using</span><span style="color: #000000;"> System.Xml;
</span><span style="color: #008080;"> 6</span> 
<span style="color: #008080;"> 7</span> <span style="color: #0000ff;">namespace</span><span style="color: #000000;"> SocketServer
</span><span style="color: #008080;"> 8</span> <span style="color: #000000;">{
</span><span style="color: #008080;"> 9</span>     <span style="color: #0000ff;">class</span><span style="color: #000000;"> XmlHandle
</span><span style="color: #008080;">10</span> <span style="color: #000000;">    {
</span><span style="color: #008080;">11</span>         <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">void</span> updatePort(<span style="color: #0000ff;">string</span> path, <span style="color: #0000ff;">string</span><span style="color: #000000;"> port)
</span><span style="color: #008080;">12</span> <span style="color: #000000;">        {
</span><span style="color: #008080;">13</span>             <span style="color: #0000ff;">try</span>
<span style="color: #008080;">14</span> <span style="color: #000000;">            {
</span><span style="color: #008080;">15</span>                 XmlTextWriter xmlWriter = <span style="color: #0000ff;">new</span> XmlTextWriter(path + <span style="color: #800000;">"</span><span style="color: #800000;">\\server.config</span><span style="color: #800000;">"</span><span style="color: #000000;">, Encoding.UTF8);
</span><span style="color: #008080;">16</span> <span style="color: #000000;">                xmlWriter.WriteStartDocument();
</span><span style="color: #008080;">17</span>                 xmlWriter.WriteStartElement(<span style="color: #800000;">"</span><span style="color: #800000;">Server</span><span style="color: #800000;">"</span><span style="color: #000000;">);
</span><span style="color: #008080;">18</span> 
<span style="color: #008080;">19</span>                 xmlWriter.WriteStartElement(<span style="color: #800000;">"</span><span style="color: #800000;">port</span><span style="color: #800000;">"</span>, <span style="color: #800000;">""</span><span style="color: #000000;">);
</span><span style="color: #008080;">20</span> <span style="color: #000000;">                xmlWriter.WriteString(port);
</span><span style="color: #008080;">21</span> <span style="color: #000000;">                xmlWriter.WriteEndElement();
</span><span style="color: #008080;">22</span> 
<span style="color: #008080;">23</span> <span style="color: #000000;">                xmlWriter.WriteEndDocument();
</span><span style="color: #008080;">24</span> <span style="color: #000000;">                xmlWriter.Close();
</span><span style="color: #008080;">25</span> <span style="color: #000000;">            }
</span><span style="color: #008080;">26</span>             <span style="color: #0000ff;">catch</span><span style="color: #000000;"> (Exception ex)
</span><span style="color: #008080;">27</span> <span style="color: #000000;">            {
</span><span style="color: #008080;">28</span> 
<span style="color: #008080;">29</span> <span style="color: #000000;">            }
</span><span style="color: #008080;">30</span> <span style="color: #000000;">        }
</span><span style="color: #008080;">31</span> 
<span style="color: #008080;">32</span> 
<span style="color: #008080;">33</span>         <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">static</span> <span style="color: #0000ff;">string</span><span style="color: #000000;"> getPort()
</span><span style="color: #008080;">34</span> <span style="color: #000000;">        {
</span><span style="color: #008080;">35</span>             <span style="color: #0000ff;">string</span> port = <span style="color: #800000;">"</span><span style="color: #800000;">8888</span><span style="color: #800000;">"</span><span style="color: #000000;">;
</span><span style="color: #008080;">36</span>             <span style="color: #0000ff;">try</span>
<span style="color: #008080;">37</span> <span style="color: #000000;">            {
</span><span style="color: #008080;">38</span>                 XmlDocument doc = <span style="color: #0000ff;">new</span><span style="color: #000000;"> XmlDocument();
</span><span style="color: #008080;">39</span>                 doc.Load(AppDomain.CurrentDomain.BaseDirectory + <span style="color: #800000;">"</span><span style="color: #800000;">\\server.config</span><span style="color: #800000;">"</span><span style="color: #000000;">);
</span><span style="color: #008080;">40</span> 
<span style="color: #008080;">41</span>                 XmlNode xnRoot = doc.SelectSingleNode(<span style="color: #800000;">"</span><span style="color: #800000;">Server</span><span style="color: #800000;">"</span><span style="color: #000000;">);
</span><span style="color: #008080;">42</span>                 XmlNodeList xnl =<span style="color: #000000;"> xnRoot.ChildNodes;
</span><span style="color: #008080;">43</span>                 <span style="color: #0000ff;">foreach</span> (XmlNode xn <span style="color: #0000ff;">in</span><span style="color: #000000;"> xnl)
</span><span style="color: #008080;">44</span> <span style="color: #000000;">                {
</span><span style="color: #008080;">45</span>                     XmlElement xe =<span style="color: #000000;"> (XmlElement)xn;
</span><span style="color: #008080;">46</span>                     <span style="color: #0000ff;">byte</span>[] bts =<span style="color: #000000;"> Encoding.UTF8.GetBytes(xe.Name);
</span><span style="color: #008080;">47</span>                     <span style="color: #0000ff;">if</span> (xe.Name == <span style="color: #800000;">"</span><span style="color: #800000;">port</span><span style="color: #800000;">"</span><span style="color: #000000;">)
</span><span style="color: #008080;">48</span> <span style="color: #000000;">                    {
</span><span style="color: #008080;">49</span>                         port =<span style="color: #000000;"> xe.InnerText;
</span><span style="color: #008080;">50</span>                         <span style="color: #0000ff;">byte</span>[] bt =<span style="color: #000000;"> Encoding.UTF8.GetBytes(port);
</span><span style="color: #008080;">51</span>                         <span style="color: #0000ff;">break</span><span style="color: #000000;">;
</span><span style="color: #008080;">52</span> <span style="color: #000000;">                    }
</span><span style="color: #008080;">53</span> <span style="color: #000000;">                }
</span><span style="color: #008080;">54</span> 
<span style="color: #008080;">55</span> <span style="color: #000000;">            }
</span><span style="color: #008080;">56</span>             <span style="color: #0000ff;">catch</span><span style="color: #000000;"> (Exception ex)
</span><span style="color: #008080;">57</span> <span style="color: #000000;">            {
</span><span style="color: #008080;">58</span> 
<span style="color: #008080;">59</span> <span style="color: #000000;">            }
</span><span style="color: #008080;">60</span>             <span style="color: #0000ff;">return</span><span style="color: #000000;"> port;
</span><span style="color: #008080;">61</span> <span style="color: #000000;">        }
</span><span style="color: #008080;">62</span> <span style="color: #000000;">    }
</span><span style="color: #008080;">63</span> }</pre>
</div>
<p>在ProjectInstaller中处理其中的逻辑，如果需要安装完成以后马上运行，那么就需要这样：</p>
<div class="cnblogs_code">
<pre><span style="color: #008080;"> 1</span> <span style="color: #0000ff;">using</span><span style="color: #000000;"> System;
</span><span style="color: #008080;"> 2</span> <span style="color: #0000ff;">using</span><span style="color: #000000;"> System.Collections;
</span><span style="color: #008080;"> 3</span> <span style="color: #0000ff;">using</span><span style="color: #000000;"> System.Collections.Generic;
</span><span style="color: #008080;"> 4</span> <span style="color: #0000ff;">using</span><span style="color: #000000;"> System.ComponentModel;
</span><span style="color: #008080;"> 5</span> <span style="color: #0000ff;">using</span><span style="color: #000000;"> System.Configuration.Install;
</span><span style="color: #008080;"> 6</span> <span style="color: #0000ff;">using</span><span style="color: #000000;"> System.Linq;
</span><span style="color: #008080;"> 7</span> 
<span style="color: #008080;"> 8</span> 
<span style="color: #008080;"> 9</span> <span style="color: #0000ff;">namespace</span><span style="color: #000000;"> SocketServer
</span><span style="color: #008080;">10</span> <span style="color: #000000;">{
</span><span style="color: #008080;">11</span>     [RunInstaller(<span style="color: #0000ff;">true</span><span style="color: #000000;">)]
</span><span style="color: #008080;">12</span>     <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">partial</span> <span style="color: #0000ff;">class</span><span style="color: #000000;"> ProjectInstaller : System.Configuration.Install.Installer
</span><span style="color: #008080;">13</span> <span style="color: #000000;">    {
</span><span style="color: #008080;">14</span>         <span style="color: #0000ff;">string</span> port = <span style="color: #800000;">""</span><span style="color: #000000;">;
</span><span style="color: #008080;">15</span>         <span style="color: #0000ff;">public</span><span style="color: #000000;"> ProjectInstaller()
</span><span style="color: #008080;">16</span> <span style="color: #000000;">        { 
</span><span style="color: #008080;">17</span> <span style="color: #000000;">            InitializeComponent();
</span><span style="color: #008080;">18</span> <span style="color: #000000;">        }
</span><span style="color: #008080;">19</span> 
<span style="color: #008080;">20</span>         <span style="color: #0000ff;">protected</span> <span style="color: #0000ff;">override</span> <span style="color: #0000ff;">void</span><span style="color: #000000;"> OnBeforeInstall(IDictionary savedState)
</span><span style="color: #008080;">21</span> <span style="color: #000000;">        {
</span><span style="color: #008080;">22</span>             <span style="color: #008000;">//</span><span style="color: #008000;">从用户界面获取的参数</span>
<span style="color: #008080;">23</span>             port = Context.Parameters[<span style="color: #800000;">"</span><span style="color: #800000;">Port</span><span style="color: #800000;">"</span><span style="color: #000000;">];
</span><span style="color: #008080;">24</span> <span style="color: #000000;">        }
</span><span style="color: #008080;">25</span> 
<span style="color: #008080;">26</span>         <span style="color: #0000ff;">protected</span> <span style="color: #0000ff;">override</span> <span style="color: #0000ff;">void</span><span style="color: #000000;"> OnAfterInstall(IDictionary savedState)
</span><span style="color: #008080;">27</span> <span style="color: #000000;">        {
</span><span style="color: #008080;">28</span>             <span style="color: #0000ff;">string</span> appPath = Context.Parameters[<span style="color: #800000;">"</span><span style="color: #800000;">targetdir</span><span style="color: #800000;">"</span><span style="color: #000000;">];
</span><span style="color: #008080;">29</span>             XmlHandle xml = <span style="color: #0000ff;">new</span><span style="color: #000000;"> XmlHandle();
</span><span style="color: #008080;">30</span> <span style="color: #000000;">            xml.updatePort(appPath, port);
</span><span style="color: #008080;">31</span>             System.ServiceProcess.ServiceController sc = <span style="color: #0000ff;">new</span><span style="color: #000000;"> System.ServiceProcess.ServiceController(serviceInstaller1.ServiceName);
</span><span style="color: #008080;">32</span>             <span style="color: #0000ff;">if</span> (sc != <span style="color: #0000ff;">null</span><span style="color: #000000;">)
</span><span style="color: #008080;">33</span> <span style="color: #000000;">            {
</span><span style="color: #008080;">34</span> <span style="color: #000000;">                sc.Start();
</span><span style="color: #008080;">35</span> <span style="color: #000000;">            }
</span><span style="color: #008080;">36</span> <span style="color: #000000;">        }
</span><span style="color: #008080;">37</span> <span style="color: #000000;">    }
</span><span style="color: #008080;">38</span> }</pre>
</div>
<p>这样就在服务安装以后服务就能启动，但是在服务启动的时候，需要从本地的配置中获取端口号，那么就需要在SocketHandle.cs中做一点点修改，改成如下的样子：</p>
<div class="cnblogs_code">
<pre><span style="color: #008080;">  1</span> <span style="color: #0000ff;">using</span><span style="color: #000000;"> System;
</span><span style="color: #008080;">  2</span> <span style="color: #0000ff;">using</span><span style="color: #000000;"> System.Collections.Generic;
</span><span style="color: #008080;">  3</span> <span style="color: #0000ff;">using</span><span style="color: #000000;"> System.Linq;
</span><span style="color: #008080;">  4</span> <span style="color: #0000ff;">using</span><span style="color: #000000;"> System.Text;
</span><span style="color: #008080;">  5</span> <span style="color: #0000ff;">using</span><span style="color: #000000;"> System.Net.Sockets;
</span><span style="color: #008080;">  6</span> <span style="color: #0000ff;">using</span><span style="color: #000000;"> System.Net;
</span><span style="color: #008080;">  7</span> <span style="color: #0000ff;">using</span><span style="color: #000000;"> System.Threading;
</span><span style="color: #008080;">  8</span> 
<span style="color: #008080;">  9</span> <span style="color: #0000ff;">namespace</span><span style="color: #000000;"> SocketServer
</span><span style="color: #008080;"> 10</span> <span style="color: #000000;">{
</span><span style="color: #008080;"> 11</span>     <span style="color: #0000ff;">class</span><span style="color: #000000;"> SocketHandle
</span><span style="color: #008080;"> 12</span> <span style="color: #000000;">    {
</span><span style="color: #008080;"> 13</span>           
<span style="color: #008080;"> 14</span>         <span style="color: #0000ff;">private</span> <span style="color: #0000ff;">string</span> pointStr =<span style="color: #000000;"> XmlHandle.getPort();
</span><span style="color: #008080;"> 15</span>         <span style="color: #0000ff;">private</span> <span style="color: #0000ff;">static</span><span style="color: #000000;"> Socket serverSocket;
</span><span style="color: #008080;"> 16</span>         <span style="color: #0000ff;">int</span> pointInt = <span style="color: #800080;">8888</span><span style="color: #000000;">;
</span><span style="color: #008080;"> 17</span>         <span style="color: #0000ff;">private</span> <span style="color: #0000ff;">static</span> <span style="color: #0000ff;">byte</span>[] result = <span style="color: #0000ff;">new</span> <span style="color: #0000ff;">byte</span>[<span style="color: #800080;">1024</span><span style="color: #000000;">];
</span><span style="color: #008080;"> 18</span>         <span style="color: #0000ff;">private</span> <span style="color: #0000ff;">static</span><span style="color: #000000;"> SocketHandle socketHandle;
</span><span style="color: #008080;"> 19</span> 
<span style="color: #008080;"> 20</span>         <span style="color: #0000ff;">public</span><span style="color: #000000;"> SocketHandle()
</span><span style="color: #008080;"> 21</span> <span style="color: #000000;">        {
</span><span style="color: #008080;"> 22</span> 
<span style="color: #008080;"> 23</span> <span style="color: #000000;">        }
</span><span style="color: #008080;"> 24</span> 
<span style="color: #008080;"> 25</span>         <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">static</span><span style="color: #000000;"> SocketHandle getInstance()
</span><span style="color: #008080;"> 26</span> <span style="color: #000000;">        {
</span><span style="color: #008080;"> 27</span>             <span style="color: #0000ff;">if</span> (socketHandle == <span style="color: #0000ff;">null</span><span style="color: #000000;">)
</span><span style="color: #008080;"> 28</span> <span style="color: #000000;">            {
</span><span style="color: #008080;"> 29</span>                 socketHandle = <span style="color: #0000ff;">new</span><span style="color: #000000;"> SocketHandle();
</span><span style="color: #008080;"> 30</span> <span style="color: #000000;">            }
</span><span style="color: #008080;"> 31</span> 
<span style="color: #008080;"> 32</span>             <span style="color: #0000ff;">return</span><span style="color: #000000;"> socketHandle;
</span><span style="color: #008080;"> 33</span> <span style="color: #000000;">        }
</span><span style="color: #008080;"> 34</span> 
<span style="color: #008080;"> 35</span>         <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">void</span><span style="color: #000000;"> InitSocketServer()
</span><span style="color: #008080;"> 36</span> <span style="color: #000000;">        {
</span><span style="color: #008080;"> 37</span>             IPAddress localIp =<span style="color: #000000;"> GetLocalIP();
</span><span style="color: #008080;"> 38</span>             <span style="color: #0000ff;">if</span> (localIp == <span style="color: #0000ff;">null</span><span style="color: #000000;">)
</span><span style="color: #008080;"> 39</span> <span style="color: #000000;">            {
</span><span style="color: #008080;"> 40</span>                 localIp = IPAddress.Parse(<span style="color: #800000;">"</span><span style="color: #800000;">127.0.0.1</span><span style="color: #800000;">"</span><span style="color: #000000;">);
</span><span style="color: #008080;"> 41</span> <span style="color: #000000;">            }
</span><span style="color: #008080;"> 42</span>             <span style="color: #0000ff;">try</span>
<span style="color: #008080;"> 43</span> <span style="color: #000000;">            {
</span><span style="color: #008080;"> 44</span>                 <span style="color: #0000ff;">if</span> (serverSocket == <span style="color: #0000ff;">null</span><span style="color: #000000;">)
</span><span style="color: #008080;"> 45</span> <span style="color: #000000;">                {
</span><span style="color: #008080;"> 46</span>                     <span style="color: #0000ff;">if</span> (pointStr <span style="color: #0000ff;">is</span> <span style="color: #0000ff;">string</span><span style="color: #000000;">)
</span><span style="color: #008080;"> 47</span> <span style="color: #000000;">                    {
</span><span style="color: #008080;"> 48</span>                         pointInt =<span style="color: #000000;"> Int32.Parse(pointStr);
</span><span style="color: #008080;"> 49</span> <span style="color: #000000;">                    }  
</span><span style="color: #008080;"> 50</span>                     serverSocket = <span style="color: #0000ff;">new</span><span style="color: #000000;"> Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);                  
</span><span style="color: #008080;"> 51</span>                     serverSocket.Bind(<span style="color: #0000ff;">new</span><span style="color: #000000;"> IPEndPoint(localIp, pointInt));
</span><span style="color: #008080;"> 52</span>                     serverSocket.Listen(<span style="color: #800080;">10</span><span style="color: #000000;">);
</span><span style="color: #008080;"> 53</span>                     Thread myThread = <span style="color: #0000ff;">new</span><span style="color: #000000;"> Thread(ListenClientConnect);
</span><span style="color: #008080;"> 54</span> <span style="color: #000000;">                    myThread.Start(); 
</span><span style="color: #008080;"> 55</span> 
<span style="color: #008080;"> 56</span> <span style="color: #000000;">                }
</span><span style="color: #008080;"> 57</span> <span style="color: #000000;">            }
</span><span style="color: #008080;"> 58</span>             <span style="color: #0000ff;">catch</span><span style="color: #000000;"> (Exception ex)
</span><span style="color: #008080;"> 59</span> <span style="color: #000000;">            { 
</span><span style="color: #008080;"> 60</span> <span style="color: #000000;">            }
</span><span style="color: #008080;"> 61</span> <span style="color: #000000;">        }
</span><span style="color: #008080;"> 62</span> 
<span style="color: #008080;"> 63</span> 
<span style="color: #008080;"> 64</span> 
<span style="color: #008080;"> 65</span>         <span style="color: #808080;">///</span> <span style="color: #808080;">&lt;summary&gt;</span>  
<span style="color: #008080;"> 66</span>         <span style="color: #808080;">///</span><span style="color: #008000;"> 监听客户端连接  
</span><span style="color: #008080;"> 67</span>         <span style="color: #808080;">///</span> <span style="color: #808080;">&lt;/summary&gt;</span>  
<span style="color: #008080;"> 68</span>         <span style="color: #0000ff;">private</span> <span style="color: #0000ff;">static</span> <span style="color: #0000ff;">void</span><span style="color: #000000;"> ListenClientConnect()
</span><span style="color: #008080;"> 69</span> <span style="color: #000000;">        {
</span><span style="color: #008080;"> 70</span>             <span style="color: #0000ff;">while</span> (<span style="color: #0000ff;">true</span><span style="color: #000000;">)
</span><span style="color: #008080;"> 71</span> <span style="color: #000000;">            {
</span><span style="color: #008080;"> 72</span>                 <span style="color: #0000ff;">try</span>
<span style="color: #008080;"> 73</span> <span style="color: #000000;">                {
</span><span style="color: #008080;"> 74</span>                     Socket clientSocket =<span style="color: #000000;"> serverSocket.Accept();
</span><span style="color: #008080;"> 75</span>                     Thread receiveThread = <span style="color: #0000ff;">new</span><span style="color: #000000;"> Thread(ReceiveMessage);
</span><span style="color: #008080;"> 76</span> <span style="color: #000000;">                    receiveThread.Start(clientSocket);
</span><span style="color: #008080;"> 77</span> <span style="color: #000000;">                }
</span><span style="color: #008080;"> 78</span>                 <span style="color: #0000ff;">catch</span><span style="color: #000000;"> (Exception ex)
</span><span style="color: #008080;"> 79</span> <span style="color: #000000;">                { 
</span><span style="color: #008080;"> 80</span> <span style="color: #000000;">                }
</span><span style="color: #008080;"> 81</span> <span style="color: #000000;">            }
</span><span style="color: #008080;"> 82</span> <span style="color: #000000;">        }
</span><span style="color: #008080;"> 83</span> 
<span style="color: #008080;"> 84</span> 
<span style="color: #008080;"> 85</span> 
<span style="color: #008080;"> 86</span>         <span style="color: #808080;">///</span> <span style="color: #808080;">&lt;summary&gt;</span>  
<span style="color: #008080;"> 87</span>         <span style="color: #808080;">///</span><span style="color: #008000;"> 接收消息  
</span><span style="color: #008080;"> 88</span>         <span style="color: #808080;">///</span> <span style="color: #808080;">&lt;/summary&gt;</span>  
<span style="color: #008080;"> 89</span>         <span style="color: #808080;">///</span> <span style="color: #808080;">&lt;param name="clientSocket"&gt;&lt;/param&gt;</span>  
<span style="color: #008080;"> 90</span>         <span style="color: #0000ff;">private</span> <span style="color: #0000ff;">static</span> <span style="color: #0000ff;">void</span> ReceiveMessage(<span style="color: #0000ff;">object</span><span style="color: #000000;"> clientSocket)
</span><span style="color: #008080;"> 91</span> <span style="color: #000000;">        {
</span><span style="color: #008080;"> 92</span>             Socket myClientSocket =<span style="color: #000000;"> (Socket)clientSocket; 
</span><span style="color: #008080;"> 93</span>             <span style="color: #0000ff;">byte</span>[] bs = <span style="color: #0000ff;">new</span> <span style="color: #0000ff;">byte</span>[<span style="color: #800080;">1024</span><span style="color: #000000;">];
</span><span style="color: #008080;"> 94</span>             <span style="color: #0000ff;">while</span> (<span style="color: #0000ff;">true</span><span style="color: #000000;">)
</span><span style="color: #008080;"> 95</span> <span style="color: #000000;">            {
</span><span style="color: #008080;"> 96</span>                 <span style="color: #0000ff;">try</span>
<span style="color: #008080;"> 97</span> <span style="color: #000000;">                {
</span><span style="color: #008080;"> 98</span>                     <span style="color: #008000;">//</span><span style="color: #008000;">通过clientSocket接收数据  </span>
<span style="color: #008080;"> 99</span>                     <span style="color: #0000ff;">int</span> receiveNumber =<span style="color: #000000;"> myClientSocket.Receive(result);
</span><span style="color: #008080;">100</span>                     <span style="color: #0000ff;">string</span> data = Encoding.ASCII.GetString(result, <span style="color: #800080;">0</span><span style="color: #000000;">, receiveNumber);
</span><span style="color: #008080;">101</span>                     bs = Encoding.ASCII.GetBytes(<span style="color: #800000;">"</span><span style="color: #800000;">Receive Data </span><span style="color: #800000;">"</span>+<span style="color: #000000;">data);
</span><span style="color: #008080;">102</span> <span style="color: #000000;">                }
</span><span style="color: #008080;">103</span>                 <span style="color: #0000ff;">catch</span><span style="color: #000000;"> (Exception ex)
</span><span style="color: #008080;">104</span> <span style="color: #000000;">                {
</span><span style="color: #008080;">105</span> <span style="color: #000000;">                    myClientSocket.Shutdown(SocketShutdown.Both);
</span><span style="color: #008080;">106</span>                     myClientSocket.Send(bs, bs.Length, <span style="color: #800080;">0</span>);  <span style="color: #008000;">//</span><span style="color: #008000;">返回信息给客户端</span>
<span style="color: #008080;">107</span> <span style="color: #000000;">                    myClientSocket.Close(); 
</span><span style="color: #008080;">108</span>                     <span style="color: #0000ff;">break</span><span style="color: #000000;">;
</span><span style="color: #008080;">109</span> <span style="color: #000000;">                }
</span><span style="color: #008080;">110</span>                 myClientSocket.Send(bs, bs.Length, <span style="color: #800080;">0</span><span style="color: #000000;">);
</span><span style="color: #008080;">111</span> <span style="color: #000000;">                myClientSocket.Close();
</span><span style="color: #008080;">112</span>                 <span style="color: #0000ff;">break</span><span style="color: #000000;">;
</span><span style="color: #008080;">113</span> <span style="color: #000000;">            }
</span><span style="color: #008080;">114</span> 
<span style="color: #008080;">115</span> <span style="color: #000000;">        }
</span><span style="color: #008080;">116</span> 
<span style="color: #008080;">117</span>         <span style="color: #808080;">///</span> <span style="color: #808080;">&lt;summary&gt;</span>
<span style="color: #008080;">118</span>         <span style="color: #808080;">///</span><span style="color: #008000;"> 获取本地IP地址
</span><span style="color: #008080;">119</span>         <span style="color: #808080;">///</span> <span style="color: #808080;">&lt;/summary&gt;</span>
<span style="color: #008080;">120</span>         <span style="color: #808080;">///</span> <span style="color: #808080;">&lt;returns&gt;&lt;/returns&gt;</span>
<span style="color: #008080;">121</span>         <span style="color: #0000ff;">private</span><span style="color: #000000;"> IPAddress GetLocalIP()
</span><span style="color: #008080;">122</span> <span style="color: #000000;">        {
</span><span style="color: #008080;">123</span>             IPAddress localIp = <span style="color: #0000ff;">null</span><span style="color: #000000;">;
</span><span style="color: #008080;">124</span>             <span style="color: #0000ff;">try</span>
<span style="color: #008080;">125</span> <span style="color: #000000;">            {
</span><span style="color: #008080;">126</span> <span style="color: #000000;">                IPAddress[] ipArray;
</span><span style="color: #008080;">127</span>                 ipArray =<span style="color: #000000;"> Dns.GetHostAddresses(Dns.GetHostName());
</span><span style="color: #008080;">128</span> 
<span style="color: #008080;">129</span>                 localIp = ipArray.First(ip =&gt; ip.AddressFamily ==<span style="color: #000000;"> AddressFamily.InterNetwork);
</span><span style="color: #008080;">130</span> <span style="color: #000000;">            }
</span><span style="color: #008080;">131</span>             <span style="color: #0000ff;">catch</span><span style="color: #000000;"> (Exception ex)
</span><span style="color: #008080;">132</span> <span style="color: #000000;">            { 
</span><span style="color: #008080;">133</span> <span style="color: #000000;">            }
</span><span style="color: #008080;">134</span> 
<span style="color: #008080;">135</span>             <span style="color: #0000ff;">return</span><span style="color: #000000;"> localIp;
</span><span style="color: #008080;">136</span> <span style="color: #000000;">        }
</span><span style="color: #008080;">137</span> <span style="color: #000000;">    }
</span><span style="color: #008080;">138</span> }</pre>
</div>
<p>下面运行一下，在看一下结果：</p>
<p>在服务的安装界面出现了添加端口的输入框：</p>
<p><img style="display: block; margin-left: auto; margin-right: auto;" src="http://images.cnitblog.com/blog/255323/201311/12135702-d65da14500bb4a65b478d1749a5db77a.png" alt="" /></p>
<p>&nbsp;</p>
<p>看端口：</p>
<p><img style="display: block; margin-left: auto; margin-right: auto;" src="http://images.cnitblog.com/blog/255323/201311/12135756-dca67cb4e3f04a8da5d15bf35ff4ecdb.png" alt="" /></p>
<p>没问题，再看Socket客户端：</p>
<p><img style="display: block; margin-left: auto; margin-right: auto;" src="http://images.cnitblog.com/blog/255323/201311/12135855-65096d1da0504bfe8f8e85c7baf5ba45.png" alt="" /></p>
<p>没问题。大概就是这样样子，如果大家觉得有什么地方不妥，或者有好的建议或者意见的话希望能够告诉我。谢谢。</p>
<p>下载地址：<a class="src-url" href="http://files.cnblogs.com/fantiantian/SocketServer.rar" target="_blank">http://files.cnblogs.com/fantiantian/SocketServer.rar</a></p></div><div id="MySignature"></div>
<div class="clear"></div>
<div id="blog_post_info_block">
<div id="BlogPostCategory"></div>
<div id="EntryTag"></div>
<div id="blog_post_info">
</div>
<div class="clear"></div>
<div id="post_next_prev"></div>
</div>


		</div>
		<div class = "postDesc">posted @ <span id="post-date">2013-11-12 14:01</span> <a href='http://www.cnblogs.com/fantiantian/'>天添</a> 阅读(<span id="post_view_count">...</span>) 评论(<span id="post_comment_count">...</span>)  <a href ="http://i.cnblogs.com/EditPosts.aspx?postid=3419401" rel="nofollow">编辑</a> <a href="#" onclick="AddToWz(3419401);return false;">收藏</a></div>
	</div>
	<script type="text/javascript">var allowComments=true,isLogined=false,cb_blogId=82470,cb_entryId=3419401,cb_blogApp=currentBlogApp,cb_blogUserGuid='5856568f-2d12-e011-ac81-842b2b196315',cb_entryCreatedDate='2013/11/12 14:01:00';loadViewCount(cb_entryId);</script>
	
</div><!--end: topics 文章、评论容器-->
</div><a name="!comments"></a><div id="blog-comments-placeholder"></div><script type="text/javascript">var commentManager = new blogCommentManager();commentManager.renderComments(0);</script>
<div id='comment_form' class='commentform'>
<a name='commentform'></a>
<div id='divCommentShow'></div>
<div id='comment_nav'><span id='span_refresh_tips'></span><a href='javascript:void(0);' onclick='return RefreshCommentList();' id='lnk_RefreshComments' runat='server' clientidmode='Static'>刷新评论</a><a href='#' onclick='return RefreshPage();'>刷新页面</a><a href='#top'>返回顶部</a></div>
<div id='comment_form_container'></div>
<div class='ad_text_commentbox' id='ad_text_under_commentbox'></div>
<div id='ad_t2'></div>
<div id='opt_under_post'></div>
<div id='ad_c1' class='c_ad_block'></div>
<div id='under_post_news'></div>
<div id='under_post_kb'></div>
<div id='HistoryToday' class='c_ad_block'></div>
<script type='text/javascript'>
$(function () {
    setTimeout(function () { incrementViewCount(cb_entryId); }, 50);
    deliverAdT2();
    deliverAdC1();    
    loadNewsAndKb();
    loadBlogSignature();
    LoadPostInfoBlock(cb_blogId, cb_entryId, cb_blogApp, cb_blogUserGuid);
    GetPrevNextPost(cb_entryId, cb_blogId, cb_entryCreatedDate);
    loadOptUnderPost();
    GetHistoryToday(cb_blogId, cb_blogApp, cb_entryCreatedDate);    
});
</script>
</div>


	</div><!--end: forFlow -->
	</div><!--end: mainContent 主体内容容器-->

	<div id="sideBar">
		<div id="sideBarMain">
			
<!--done-->
<div class="newsItem">
<h3 class="catListTitle">公告</h3>
	<div id="blog-news"></div><script type="text/javascript">loadBlogNews();</script>
</div>

			<div id="blog-calendar" style="display:none"></div><script type="text/javascript">loadBlogDefaultCalendar();</script>
			
			<div id="leftcontentcontainer">
				<div id="blog-sidecolumn"></div><script type="text/javascript">loadBlogSideColumn();</script>
			</div>
			
		</div><!--end: sideBarMain -->
	</div><!--end: sideBar 侧边栏容器 -->
	<div class="clear"></div>
	</div><!--end: main -->
	<div class="clear"></div>
	<div id="footer">
		
<!--done-->
Copyright &copy;2016 天添
	</div><!--end: footer -->
</div><!--end: home 自定义的最大容器 -->
</body>
</html>
